package com.lcm.jnode.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.plugin.redis.RedisKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JadeXmlRender;
import com.lcm.jnode.interceptor.SidebarInterceptor;
import com.lcm.jnode.kit.ImageKit;
import com.lcm.jnode.kit.MailKit;
import com.lcm.jnode.model.Blog;
import com.lcm.jnode.model.MailVerify;
import com.lcm.jnode.model.User;
import com.lcm.jnode.utils.ConfigUtil;
import com.lcm.jnode.utils.DateUtil;

/**
 * 首页
 * @author L.cm
 * @date 2013-5-7 上午9:42:21
 */
@Before(SidebarInterceptor.class)
public class IndexController extends Controller{

    /**
     * 首页
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void index() {
        Map<String, Object> result = Maps.newHashMap();
        result.put(Blog.BLOG_TYPE, null);
        Page<Blog> page = Blog.dao.page(getParaToInt(0, 1), 8, result);
        setAttr("postsby", false);
        setAttr("blogPage", page);
    }
    
    /**
     * 文章
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void blogs() {
        Map<String, Object> result = Maps.newHashMap();
        result.put(Blog.BLOG_TYPE, 0);
        Page<Blog> page = Blog.dao.page(getParaToInt(0, 1), 6, result);
        setAttr("blogPage", page);
        setAttr("postsby", Blog.TYPE_NAME[0]);
        setAttr("pageUrl", "/blogs");
        render("index");
    }
    
    /**
     * 收藏
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void favorites() {
        Map<String, Object> result = Maps.newHashMap();
        result.put(Blog.BLOG_TYPE, 1);
        Page<Blog> page = Blog.dao.page(getParaToInt(0, 1), 6, result);
        setAttr("blogPage", page);
        setAttr("postsby", Blog.TYPE_NAME[1]);
        setAttr("pageUrl", "/favorites");
        render("index");
    }
    
    /**
     * 搜索
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void search() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("s", getPara("s"));
        Page<Blog> page = Blog.dao.page(getParaToInt(0, 1), 6, result);
        setAttr("keywords", getPara("s"));
        setAttr("blogPage", page);
        setAttr("postsby", "搜索");
        setAttr("pageUrl", "/search");
        render("index");
    }
    
    public void t() {
    	List<Object> l = new ArrayList<Object>();
		l.add("hello");
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("1", 1);
		map.put("2", 2);
		
		l.add(map);
    	RedisKit.setListAsTimeout("test", l, 5);
    	renderJson(RedisKit.getAsList("test"));
    }
    
    // 验证码测试
    public void tt() {
    	Map<String, String> vcodeMap = ImageKit.cenerateVCode();
    	setSessionAttr("vcode_secret", vcodeMap.get("secret"));
    	// {"secret":"","imgurl":""}
		renderJson(vcodeMap);
    }
    
    // 验证码测试
    public void tv() {
    	String input = getPara("code", "");
    	String secret = getSessionAttr("vcode_secret");
    	// {"reason":"success","status":"0"} 
    	// status == '0' 正确 
    	renderJson(ImageKit.verifyVCode(input, secret));
    }

    public void test() {
        String email = getPara("email", "453871784@qq.com");
    	Map<String, Object> model = Maps.newHashMap();
    	model.put("user", "大黄");
		model.put("baseUrl", "http://dreamlu.net/");
		model.put("verifyUrl", "http://dreamlu.net/");
		MailKit.sendTemplateEmail(ConfigUtil.get("from"), "测试邮件", email, model, "signup_send.jade");
		renderNull();
    }
    
    /**
     * 关于
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void about() {}
    
    /**
     * 登录
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void sign_in() {
        User user = getSessionAttr("user");
        if(StringKit.notNull(user)) {
            redirect("/admin");
        }else {
            render("admin/sign-in");
        }
    }
    
    /**
     * 重置密码
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void reset_pwd() {
    	String mailTo = getPara("email");
    	Map<String, Object> model = new HashMap<String, Object>();
    	User user = User.dao.findByEmail(mailTo);
    	boolean status = false;
    	if (StringKit.notNull(user)) {
        	MailVerify mv = new MailVerify();
        	mv.set(MailVerify.USER_ID, user.getInt(User.ID));
        	String code = DigestUtils.md5Hex(mailTo + System.currentTimeMillis());
        	mv.set(MailVerify.VERIFY_CODE, code);
        	mv.set(MailVerify.CREATE_TIME, new Date());
        	mv.set(MailVerify.UPDATE_TIME, new Date());
        	boolean temp = mv.save();
        	if (temp) {
        		model.put("user", user.getStr(User.NICK_NAME));
        		model.put("baseUrl", "http://www.dreamlu.net/");
        		model.put("verifyUrl", "http://www.dreamlu.net/finish?code=" + code);
        		// TODO BAE email send
//        		status = MailUtils.sendTemplateEmail("找回密码-DreamLu.net", mailTo, model, "signup_send.jade");
        	}
    	}
    	renderJson("status", status);
    }
    
    /**
     * 邮箱返回连接
     */
    public void finish() {
    	String code = getPara("code");
    	MailVerify mv = MailVerify.dao.getByCode(code);
    	Date createTime = mv.getTimestamp("CREATE_TIME");
    	if (null != mv && createTime.after(DateUtil.hourBefor(24)) && mv.getInt(MailVerify.DEL_STATUS) == MailVerify.DEL_N) {
    		boolean temp = mv.set(MailVerify.DEL_STATUS, MailVerify.DEL_Y).set(MailVerify.UPDATE_TIME, new Date()).update();
    		if (temp) {
    			User user = User.dao.findById(mv.getInt(MailVerify.USER_ID));
    			user.set(User.EMAIL_VERIFY, User.EMAIL_Y);
    			User.dao.updateUser(user);
    			setSessionAttr("user", user);
    		}
    		redirect("/admin");
    	} else {
    		redirect("/");
    	}
    }
    
    
    /**
     * 登出
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void logout() {
        removeCookie("userId", "/", ConfigUtil.get("domain"));
        removeSessionAttr("user");
        redirect("sign_in");
    }
    
    /**
     * 提供给github pages jsonp跨域使用
     * @url         http://dreamlu.net/
     * @param       设定文件
     * @return void    返回类型
     * @throws
     */
    public void json() {
    	String callback = getPara("callback");
    	List<Blog> blogs = Blog.dao.find4github();
    	getResponse().setHeader("Access-Control-Allow-Origin", "*");
    	if (StringKit.isBlank(callback)) {
    		renderJson(JsonKit.listToJson(blogs, 2));
    	} else {
    		renderJavascript(getPara("callback") + "(" + JsonKit.listToJson(blogs, 2) + ")");
    	}
    }
    
    /**
     * rss 订阅最新20条
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void rss() {
    	List<Blog> rssList = Blog.dao.rssList(20);
    	setAttr("rssList", rssList);
    	render(new JadeXmlRender("xml_template/rss"));
    }
}
